package cn.edu.scau.config;


import cn.edu.scau.converter.MyDateConvert;
import cn.edu.scau.intercepter.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.filter.FormContentFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * 配置类OfficeConfig：针对项目的全局配置
 */
@SpringBootConfiguration
public class OfficeConfig extends WebMvcConfigurationSupport {
    @Autowired
    private MyDateConvert myDateConvert;
    @Autowired
    private LoginInterceptor loginInterceptor;

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor)//注册拦截器
        .addPathPatterns("/**")//拦截用户所有请求
         .excludePathPatterns("/css/**","/js/**","images/**",
                 "/webjars/**","/login","/checklogin","/exit","/swagger-ui.html","/v2/**","/swagger-resources/**"
         ,"/druid/**","/error/**");//拦截例外
        super.addInterceptors(registry);
    }

    /**
     * 解决PUT请求无法获取
     * @return
     */
    @Bean
    public FormContentFilter FormContentFilter(){
        return new FormContentFilter();
    }
    @Override
    protected void addFormatters(FormatterRegistry registry) {
        registry.addConverter(myDateConvert);
        super.addFormatters(registry);
    }

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
        .addResourceLocations("classpath:/META-INF/resources/")
        .addResourceLocations("classpath:/resources/")
        .addResourceLocations("classpath:/public/")
        .addResourceLocations("classpath:/static/")
        .addResourceLocations("classpath:/templates/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("/webjars/").resourceChain(false);
        super.addResourceHandlers(registry);
    }

    @Override
    protected void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*").allowCredentials(true)
                .allowedMethods("GET","POST","PUT","DELETE","PATCH","OPTIONS","HEAD").maxAge(3600*48);
        super.addCorsMappings(registry);
    }

}
